package com.ruoyi.project.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.SmAutonomy;
import com.ruoyi.project.system.domain.SmPay;
import com.ruoyi.project.system.domain.SmProduct;
import com.ruoyi.project.system.domain.SmQuery;
import com.ruoyi.project.system.domain.dto.ThrEleResult;
import com.ruoyi.project.system.domain.vo.QueryVo;
import com.ruoyi.project.system.domain.vo.Record;
import com.ruoyi.project.system.mapper.SmQueryMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.ISmPayService;
import com.ruoyi.project.system.service.ISmProductService;
import com.ruoyi.project.system.service.ISmQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.List;
import static com.ruoyi.common.utils.http.HttpUtils.sendPost;
import static com.ruoyi.common.utils.uuid.Seq.getId;
import static com.ruoyi.framework.web.domain.AjaxResult.error;
import static com.ruoyi.framework.web.domain.AjaxResult.success;
import static com.ruoyi.project.utils.SmHandler.queryDataHandler;

/**
 * 查询进件Service业务层处理
 */
@Service
public class SmQueryServiceImpl implements ISmQueryService {

    @Autowired
    private ISmProductService smProductService;

    @Autowired
    private ISmPayService smPayService;

    @Autowired
    private SmQueryMapper smQueryMapper;

    @Autowired
    private SysUserMapper userMapper;

    public AjaxResult getAjaxResult(SmQuery smQuery, String endTime) {
        AjaxResult query;
        if (smQuery != null && StringUtils.isNotEmpty(smQuery.getQueryInfo())) {
            query = new AjaxResult();
            query.putAll(JSONObject.parseObject(smQuery.getQueryInfo()));
        } else {
            if (smQuery.getProductId() == 1) {
                query = this.bigDataQueryPro(smQuery);
            } else if (smQuery.getProductId() == 2) {
                query = this.bigDataQuery(smQuery);
            } else if (smQuery.getProductId() == 4) {
                query = this.marryQuery(smQuery);
            } else if (smQuery.getProductId() == 5) {
                query = this.judicialQuery(smQuery);
            } else if (smQuery.getProductId() == 7) {
                query = this.education(smQuery);
            } else if (smQuery.getProductId() == 8) {
                query = this.military(smQuery);
            } else {
                return error("没有此产品编号！");
            }
            for (String key : query.keySet()) {
                JSONObject value = (JSONObject) query.get(key);
                if (value.get("retdata") instanceof String) {
                    if (!"000000".equals(value.getString("retcode"))) {
                        return error("数据出错！");
                    }
                    String retdata = value.getString("retdata");
                    if ('[' == retdata.charAt(0)) {
                        value.replace("retdata", JSON.parseArray(retdata));
                    } else if ('{' == retdata.charAt(0)) {
                        value.replace("retdata", JSON.parseObject(retdata));
                    }
                    query.replace(key, value);
                }
            }
            smQueryMapper.updateSmQuery(new SmQuery(smQuery.getId(), JSON.toJSONString(query)));
        }
        return success(queryDataHandler(query, smQuery, endTime));
    }

    @Override
    public JSONObject companyQuery(SmQuery smQuery) {
        JSONObject params = new JSONObject();
        String baseReqSn = "QXY" + getId();
        params.put("req_time", System.currentTimeMillis());
        // 个人诉讼
        params.put("request_sn", baseReqSn + "JF033");
        params.put("inter_id", "JF033");
        params.put("mobile", smQuery.getTel());
        return JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params));
    }

    @Override
    @Transactional
    public AjaxResult selfQueryPay(SmQuery smQuery) {
        // 1. 构建支付订单
        Long userId = smQuery.getUserId();
        Integer productId = smQuery.getProductId();
        Integer roleId = userMapper.queryRoleId(userId);
        SmProduct smProduct = smProductService.selectSmProductById(productId);
        BigDecimal pricing = smProductService.userBasePrice(userId, roleId, smProduct);
        SmPay smPay = new SmPay(smQuery, "self_query", pricing, smProduct.getName() + "自用查询付费");
        // 2. 写入支付订单
        smPayService.insertSmPay(smPay);
        // 3. 计算写入收益
        smPayService.calculateCommonIncome(smPay, roleId, smProduct);
        // 4. 发起支付
        try {
            JSONObject payInfo = smPayService.zhifuFM(smPay, smProduct.getCode());
            payInfo.put("orderNo", smPay.getOrderNo());
            payInfo.put("id", smQuery.getId());
            return success(payInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return error("发起支付异常！");
        }
    }

    @Override
    @Transactional
    public AjaxResult promotionQueryPay(SmQuery smQuery) {
        // 1. 构建支付订单
        Long userId = smQuery.getUserId();
        Integer productId = smQuery.getProductId();
        Integer roleId = userMapper.queryRoleId(userId.longValue());
        SmProduct smProduct = smProductService.selectSmProductById(productId);
        BigDecimal pricing = smProductService.promotionPrice(userId.longValue(), roleId, smProduct);
        SmPay smPay = new SmPay(smQuery, "other_query", pricing, smProduct.getName() + "他人查询付费");
        // 2. 写入支付订单
        smPayService.insertSmPay(smPay);
        // 3. 计算写入收益
        smPayService.calculatePromotionIncome(smPay, roleId, smProduct);
        // 4. 发起支付
        try {
            JSONObject payInfo = smPayService.zhifuFM(smPay, smProduct.getCode());
            payInfo.put("orderNo", smPay.getOrderNo());
            return success(payInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return error("发起支付异常！");
        }
    }

    @Override
    public AjaxResult judicialQuery(SmQuery smQuery) {
        AjaxResult result = new AjaxResult();
        JSONObject params = new JSONObject();
        params.put("req_time", System.currentTimeMillis());
        params.put("request_sn", "QXY" + getId() + "JF025");
        params.put("inter_id", "JF025");
        params.put("name", smQuery.getName());
        params.put("cardNo", smQuery.getCardNo());
        result.put("grss", JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        return result;
    }

    @Override
    public AjaxResult bigDataQuery(SmQuery smQuery) {
        AjaxResult result = new AjaxResult();
        JSONObject params = new JSONObject();
        params.put("req_time", System.currentTimeMillis());
        params.put("request_sn", "QXY" + getId()  + "JF011");
        params.put("inter_id", "JF011");
        params.put("name", smQuery.getName());
        params.put("cardNo", smQuery.getCardNo());
        params.put("mobile", smQuery.getTel());
        result.put("dttz", JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        return result;
    }

    @Override
    public AjaxResult bigDataQueryPro(SmQuery smQuery) {
        AjaxResult result = new AjaxResult();
        JSONObject params = new JSONObject();
        String baseReqSn = "QXY" + getId();
        params.put("req_time", System.currentTimeMillis());
        // 个人诉讼
        //        params.put("request_sn", baseReqSn + "JF025");
        //        params.put("inter_id", "JF025");
        //        params.put("name", smQuery.getName());
        //        params.put("cardNo", smQuery.getCardNo());
        //        result.put("grss", JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        // 手机三要素
        params.put("request_sn", baseReqSn + "JF007");
        params.put("inter_id", "JF007");
        params.put("name", smQuery.getName());
        params.put("cardNo", smQuery.getCardNo());
        params.put("mobile", smQuery.getTel());
        result.put("sjsys", JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        // 多头
        params.replace("request_sn", baseReqSn + "JF011");
        params.replace("inter_id", "JF011");
        result.put("dttz", JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        // 借选指数
        params.replace("request_sn", baseReqSn + "JF010");
        params.replace("inter_id", "JF010");
        result.put("jxzs", JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        // 特殊名单验证
//        String[] labelsList = sysBlacklistMapper.selectLabelsList(new SysBlacklist(smQuery));
        JSONArray includes = new JSONArray();
//        for (String labels : labelsList) {
//            JSONArray array = JSON.parseArray(labels);
//            for (int i = 0; i < array.size(); i++) {
//                String label = array.getString(i);
//                if (!includes.contains(label)) {
//                    includes.add(label);
//                }
//            }
//        }
        JSONObject labels = new JSONObject();
        labels.put("retcode", "000000");
        labels.put("retdata", includes.toJSONString());
        result.put("labels", labels);
        return result;
    }

    @Override
    public AjaxResult marryQuery(SmQuery smQuery) {
        AjaxResult result = new AjaxResult();
        JSONObject params = new JSONObject();
        String baseReqSn = "QXY" + getId() ;
        params.put("req_time", System.currentTimeMillis());
        // 实名认证
        params.put("request_sn", baseReqSn + "JF005");
        params.put("inter_id", "JF005");
        params.put("name", smQuery.getName());
        params.put("cardNo", smQuery.getCardNo());
        result.put("smrz", JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        // 个人诉讼
        params.replace("request_sn", baseReqSn + "JF025");
        params.replace("inter_id", "JF025");
        result.put("grss", JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        // 婚姻
//        params.put("mobile", smQuery.getMobile());
        params.replace("request_sn", baseReqSn + "JF032");
        params.replace("inter_id", "JF032");
        result.put("hyhy", JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));

//        SMSUtils.sendReport(smQuery.getTel(), "mar", orderNo);

        return result;
    }

    @Override
    public AjaxResult education(SmQuery smQuery) {
        AjaxResult result = new AjaxResult();
        JSONObject params = new JSONObject();
        String baseReqSn = "QXY" + getId();
        params.put("req_time", System.currentTimeMillis());
        // 实名认证
        params.put("request_sn", baseReqSn + "JF005");
        params.put("inter_id", "JF005");
        params.put("name", smQuery.getName());
        params.put("cardNo", smQuery.getCardNo());
        result.put("smrz", JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        // 学历查询
        params.replace("request_sn", baseReqSn + "JF003");
        params.replace("inter_id", "JF003");
        result.put("xlxx", JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));

        // 手机三要素
        params.replace("request_sn", baseReqSn + "JF007");
        params.replace("inter_id", "JF007");
        params.put("mobile", smQuery.getTel());
        result.put("sjsys", JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        return result;
    }

    @Override
    public AjaxResult military(SmQuery smQuery) {
        AjaxResult result = new AjaxResult();
        JSONObject params = new JSONObject();
        String baseReqSn = "QXY" + getId() ;
        params.put("req_time", System.currentTimeMillis());
        // 实名认证
        params.put("request_sn", baseReqSn + "JF005");
        params.put("inter_id", "JF005");
        params.put("name", smQuery.getName());
        params.put("cardNo", smQuery.getCardNo());
        result.put("smrz", JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        // 手机三要素
        params.replace("request_sn", baseReqSn + "JF007");
        params.replace("inter_id", "JF007");
        params.put("mobile", smQuery.getTel());
        result.put("sjsys", JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        return result;
    }

    @Override
    public ThrEleResult verificationThrEle(SmAutonomy smAutonomy) {
        // 核验三要素
        JSONObject params = new JSONObject();
        params.put("req_time", System.currentTimeMillis());
        params.put("request_sn", "QXY" + getId()  + "JF060");
        params.put("inter_id", "JF060");
        params.put("name", smAutonomy.getName());
        params.put("cardNo", smAutonomy.getCardNo());
        params.put("mobile", smAutonomy.getTel());
        try {
            JSONObject sjsys = JSON.parseObject(sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params));
            if (sjsys.containsKey("retcode") && "000000".equals(sjsys.getString("retcode"))) {
                JSONObject data = sjsys.getJSONObject("retdata");
                Integer busiCode = data.getInteger("busiCode");
                if (busiCode == 10) {
                    Integer status = data.getJSONObject("result").getInteger("status");
                    if (status == 1) {
                        smAutonomy.setMsg("一致");
                        smAutonomy.setPass("Y");
                        return new ThrEleResult(smAutonomy);
                    } else if (status == 2) {
                        smAutonomy.setMsg("不一致");
                        smAutonomy.setPass("N");
                        return new ThrEleResult("仅允许本人查询",smAutonomy);
                    } else {
                        smAutonomy.setMsg("查无数据");
                        return new ThrEleResult("实名核验查无数据",smAutonomy);
                    }
                } else if (busiCode == 1007) {
                    smAutonomy.setMsg(data.getString("busiMsg"));
                    return new ThrEleResult(data.getString("busiMsg"),smAutonomy);
                } else {
                    smAutonomy.setMsg("实名核验异常");
                    return new ThrEleResult("实名核验异常",smAutonomy);
                }
            } else {
                smAutonomy.setMsg("实名核验失败");
                return new ThrEleResult("实名核验失败",smAutonomy);
            }
        } catch (Exception e) {
            e.printStackTrace();
            smAutonomy.setMsg("实名核验异常");
            return new ThrEleResult("实名核验异常",smAutonomy);
        }
    }

    @Override
    public void autonomy(SmAutonomy smAutonomy) {
        Long userId = smAutonomy.getUserId();
        Integer i = smQueryMapper.selectAutonomyByUserId(userId);
        if (i == null) {
            smQueryMapper.insertAutonomy(smAutonomy);
        } else {
            smAutonomy.setId(i);
            smQueryMapper.updateAutonomy(smAutonomy);
        }
    }

    @Override
    public List<Record> getRecords(String mobile, String sign) {
        List<Record> recordList = smQueryMapper.recordList(mobile, sign);
        // 处理数据
        for (Record record : recordList) {
            if (record.getProductId() == 3) {         // 企业 MK
                String m = record.getMobile();
                String mk = record.getMoreKeyword();
                record.setMoreKeyword(StringUtils.isEmpty(mk) ? m : mk);
            } else {
                record.setMoreKeyword(StringUtils.isEmpty(record.getName()) ? "查询关键字不全" : ("**" + record.getName().substring(1)));
            }
            record.setPayState("SUCCESS".equals(record.getPayState()) ? "-查询完成" : "");
            record.setName(null);
            record.setCardNo(null);
            record.setMobile(null);
        }
        return recordList;
    }

    /**
     * 查询查询进件
     *
     * @param id 查询进件主键
     * @return 查询进件
     */
    @Override
    public SmQuery selectSmQueryById(Integer id) {
        return smQueryMapper.selectSmQueryById(id);
    }

    /**
     * 查询查询进件列表
     *
     * @param queryVo 查询进件
     * @return 查询进件
     */
    @Override
    public List<QueryVo> selectSmQueryList(QueryVo queryVo) {
        return smQueryMapper.selectSmQueryList(queryVo);
    }

    /**
     * 新增查询进件
     *
     * @param smQuery 查询进件
     * @return 结果
     */
    @Override
    public int insertSmQuery(SmQuery smQuery) {
        return smQueryMapper.insertSmQuery(smQuery);
    }

    /**
     * 修改查询进件
     *
     * @param smQuery 查询进件
     * @return 结果
     */
    @Override
    public int updateSmQuery(SmQuery smQuery) {
        return smQueryMapper.updateSmQuery(smQuery);
    }

    /**
     * 批量删除查询进件
     *
     * @param ids 需要删除的查询进件主键
     * @return 结果
     */
    @Override
    public int deleteSmQueryByIds(Integer[] ids) {
        return smQueryMapper.deleteSmQueryByIds(ids);
    }

}
